package com.example.myapplication2030606131wjw;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {


    private RecyclerView rvMainNews;
    String url="http://192.168.29.230:3000/news";

    OkHttpClient okHttpClient =new OkHttpClient();

    Gson gson= new Gson();
    Type type = new TypeToken<List<News>>(){}.getType();
    List<News> newsList= new ArrayList<>();
    NewsRVAdapter newsRVAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        rvMainNews.setLayoutManager(new LinearLayoutManager(this));

        new  Thread(new Runnable() {
            @Override
            public void run() {
                Request request =new Request.Builder()
                        .url(url)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                  String result = response.body().string();
                  newsList= gson.fromJson(result,type);
                        Log.i("TAG","onResponse:"+newsList.size());
                        newsRVAdapter= new NewsRVAdapter(newsList);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rvMainNews.setAdapter(newsRVAdapter);
                            }
                        });
                    }
                });
            }
        }).start();
    }

    private void initView() {
        rvMainNews = (RecyclerView) findViewById(R.id.rvMainNews);
    }
}